package com.yanqu.road.server.gameplayer.module.match;

import com.yanqu.road.entity.config.match.MatchInfo;
import com.yanqu.road.entity.config.match.MatchReward;
import com.yanqu.road.entity.config.patrons.PatronsInfo;
import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.entity.enums.eSystemId;
import com.yanqu.road.entity.log.LogVarietyDispatch;
import com.yanqu.road.entity.log.LogVarietyRank;
import com.yanqu.road.entity.match.MatchPatronsData;
import com.yanqu.road.entity.match.MatchRewardResult;
import com.yanqu.road.entity.match.MatchTimeData;
import com.yanqu.road.entity.match.MatchWeekRankRewardState;
import com.yanqu.road.entity.player.UserPatrons;
import com.yanqu.road.logic.bussiness.match.MatchBussiness;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.pb.variety.VarietyProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.gameplayer.module.patrons.PatronsModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.gameplayer.module.player.PreReduceModule;
import com.yanqu.road.server.manger.config.PatronsMgr;
import com.yanqu.road.server.manger.config.SystemOpenMgr;
import com.yanqu.road.server.manger.log.LogMgr;
import com.yanqu.road.server.manger.match.MatchMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.pb.PlayerPb;
import com.yanqu.road.server.pb.VarietyPb;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;

import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author ：zfr
 * @date ：2021/2/4 16:22
 */
public class MatchModule extends GeneralModule {
    /**
     * 杂艺系统玩家门客数据
     * patronsId - MatchPatronsData
     */
    private Map<Integer, MatchPatronsData> dataMap;

    /**
     * 玩家时间点数据（派遣&领奖）
     */
    private Map<Integer, Map<Integer, MatchTimeData>> matchTimeDataMap;

    private Map<Integer, MatchWeekRankRewardState> rewardStateMap;

    public Map<Integer, MatchWeekRankRewardState> getRewardStateMap() {
        return rewardStateMap;
    }

    public MatchModule(GamePlayer player) {
        super(player);
    }

    @Override
    public boolean loadData() {
        dataMap = MatchBussiness.getMatchPatronsDataMap(getUserId());
        matchTimeDataMap = MatchBussiness.getMatchTimeData(getUserId());
        rewardStateMap = MatchBussiness.getMatchWeekRankRewardStateMap(getUserId());
        return true;
    }

    //时间格式YyyyMmDd
    public static int parseTimeId(long time) {
        return Integer.valueOf(DateHelper.getPyyyyMMddDateString(time / 1000));
    }

    /**
     * 初始化玩家时间数据
     */
    private void addMatchTimeData(int id) {
        MatchTimeData matchTimeData = new MatchTimeData();
        matchTimeData.setUserId(getUserId());
        matchTimeData.setDispatchTimeId(parseTimeId(System.currentTimeMillis()));
        matchTimeData.setGetRewardTime(0L);
        matchTimeData.setId(id);
        matchTimeData.setInsertOption();
        if (!matchTimeDataMap.containsKey(matchTimeData.getDispatchTimeId())) {
            matchTimeDataMap.put(matchTimeData.getDispatchTimeId(), new ConcurrentHashMap<>());
        }
        matchTimeDataMap.get(matchTimeData.getDispatchTimeId()).put(matchTimeData.getId(), matchTimeData);
    }

    @Override
    public boolean afterLoadData() {
        return false;
    }

    @Override
    public boolean saveData() {
        for (MatchPatronsData data : dataMap.values()) {
            if (data.isInsertOption()) {
                MatchBussiness.addData(data);
            } else if (data.isUpdateOption()) {
                MatchBussiness.updateData(data);
            }
        }
        for (Map<Integer, MatchTimeData> map : matchTimeDataMap.values()) {
            for (MatchTimeData matchTimeData : map.values()) {
                if (matchTimeData.isInsertOption()) {
                    MatchBussiness.addData(matchTimeData);
                } else if (matchTimeData.isUpdateOption()) {
                    MatchBussiness.updateData(matchTimeData);
                }
            }
        }
        for (MatchWeekRankRewardState state : rewardStateMap.values()) {
            if (state.isInsertOption()) {
                MatchBussiness.addMatchWeekRankRewardState(state);
            } else if (state.isUpdateOption()) {
                MatchBussiness.upMatchWeekRankRewardState(state);
            }

        }

        return true;
    }

    /**
     * 派遣队伍
     *
     * @param id         杂艺自增id
     * @param level      杂艺等级
     * @param occupation 杂艺职业类型
     * @param matchId    杂艺id
     * @param patronsIds 派遣门客列表
     * @return ret 结果
     */
    public int dispatchTeam(int id, int level, int occupation, int matchId, List<Integer> patronsIds) {
        // 身份解锁
        if (!SystemOpenMgr.systemOpen(player, eSystemId.Variety.getValue())) {
            return GameErrorCode.E_SYSTEM_NO_OPEN;
        }
        //检查门客合法性
        int ret = checkPatrons(patronsIds, occupation);
        if (ret != 0) {
            return ret;
        }
        //检查参赛时间
        if (!checkIsInDispatchTime()) {
            return GameErrorCode.E_VARIETY_PATRONS_NOT_JOIN_TIME;
        }
        //派遣消耗
        MatchInfo matchInfo = MatchMgr.getMatchInfo(level, matchId);
        if (matchInfo == null) {
            return GameErrorCode.E_VARIETY_VARIETY_NOT_FOUND;
        }
        if (!player.getModule(CurrencyModule.class).currencyIsEnough(PropertyHelper.parseStringToProperty(matchInfo.getConsume()))) {
            return GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
        }
        //预扣除派遣消耗
        player.getModule(PreReduceModule.class).preReduce(matchInfo.getConsume());
        //都通过了 预扣除一下门客出战次数
        for (Integer patronsId : patronsIds) {
            dataMap.get(patronsId).setPreMatchBattleTimes(1);
        }
        //发送跨服派遣
        player.sendPacket(CrossProtocol.C_VARIETY_DISPATCH_TEAM, VarietyPb.parseDispatchReq(id, level, occupation, matchId, patronsIds, player));
        return 0;
    }

    /**
     * 派遣队伍跨服返回
     *
     * @param id
     * @param level
     * @param matchId
     * @param patronsIds 派遣门客id列表
     * @param ret        结果
     */
    public void dispatchTeamFromCross(int id, int level, int matchId, List<Integer> patronsIds, int ret) {
        //恢复预扣除项
        MatchInfo matchInfo = MatchMgr.getMatchInfo(level, matchId);
        if (matchInfo != null) {
            player.getModule(PreReduceModule.class).restorePreReduce(matchInfo.getConsume());
        }
        for (Integer patronsId : patronsIds) {
            MatchPatronsData data = dataMap.get(patronsId);
            if (data != null) {
                //恢复预扣除出战次数
                data.setPreMatchBattleTimes(0);
                if (ret == 0) {
                    //派遣成功 出战次数+1
                    data.setMatchBattleTimes(data.getMatchBattleTimes() + 1);
                    data.setBattleTimeId(parseTimeId(System.currentTimeMillis()));
                }
            }
        }
        if (ret == 0) {
            player.getModule(CurrencyModule.class).removeCurrency(PropertyHelper.parseStringToProperty(matchInfo.getConsume()), eLogMoneyType.Variety, eLogMoneyType.VarietyDispatchCost);
            //设置一下派遣时间
            addMatchTimeData(id);
            //同步门客出战次数
            syncVarietyPatrons();
            try {
                BigInteger earnSpeed = BigInteger.ZERO;
                for (Integer patronsId : patronsIds) {
                    earnSpeed = earnSpeed.add(player.getModule(PatronsModule.class).getUserPatrons(patronsId).getAbility());
                }
                LogMgr.addLogVarietyDispatch(new LogVarietyDispatch(getUserId(), matchInfo.getOccupation(), matchInfo.getLevel(),
                        patronsIds.size(), patronsIds, earnSpeed, new Date()));
            } catch (Exception ex) {
                log.error("add varietyDispatch log error, userId:{}", getUserId());
            }
        }
        VarietyProto.DispatchTeamRespMsg.Builder builder = VarietyProto.DispatchTeamRespMsg.newBuilder();
        builder.setRet(ret);
        player.sendPacket(ClientProtocol.U_VARIETY_DISPATCH_TEAM, builder);
    }

    @Override
    public void afterLogin() {
        //同步玩家杂艺门客出战次数
        syncVarietyPatrons();
        //同步区服分组
        VarietyProto.SyncGroupServerReqMsg.Builder groupServerListSyncMsg = VarietyProto.SyncGroupServerReqMsg.newBuilder();
        player.sendPacket(CrossProtocol.C_VARIETY_SYNC_GROUP_SERVER_LIST, groupServerListSyncMsg);
    }

    /**
     * 检查派遣时间合法性
     */
    private boolean checkIsInDispatchTime() {
        long zeroTime = DateHelper.getTodayZeroTimeStamp();
        long nowTime = System.currentTimeMillis();
        return (nowTime >= (zeroTime + GameConfig.VARIETY_BEGIN_TIME * 60 * 1000) && nowTime <= (zeroTime + GameConfig.VARIETY_END_TIME * 60 * 1000));
    }

    /**
     * 检查是否过派遣期
     *
     * @return
     */
    private boolean checkIsOverDispatchTime() {
        long zeroTime = DateHelper.getTodayZeroTimeStamp();
        long nowTime = System.currentTimeMillis();
        return nowTime > (zeroTime + GameConfig.VARIETY_BEGIN_TIME * 60 * 1000);
    }

    private boolean checkIsLastRewardTime() {
        long zeroTime = DateHelper.getTodayZeroTimeStamp();
        long nowTime = System.currentTimeMillis();
        return nowTime >= (zeroTime + GameConfig.VARIETY_END_TIME * 60 * 1000);
    }

    private boolean checkInCanRewardTime() {
        long zeroTime = DateHelper.getTodayZeroTimeStamp();
        long nowTime = System.currentTimeMillis();
        return nowTime >= (zeroTime + (GameConfig.VARIETY_END_TIME + 5) * 60 * 1000);
    }

    /**
     * 检查门客合法性
     *
     * @param patronsIds 门客id列表
     * @param occupation
     * @return ret 结果
     */
    private int checkPatrons(List<Integer> patronsIds, int occupation) {
         if (patronsIds.size() <= 0 || patronsIds.size() > GameConfig.VARIETY_TEAM_PATRONS_MAX_COUNT) {
            //派遣门客数量错误
            return GameErrorCode.E_VARIETY_DISPATCH_PATRONS_NUM_ERROR;
        }
        if (new HashSet<>(patronsIds).size() != patronsIds.size()) {
            //门客重复派遣
            return GameErrorCode.E_VARIETY_DISPATCH_PATRONS_REPEATED;
        }
        for (Integer patronsId : patronsIds) {
            //门客未拥有
            UserPatrons userPatrons = player.getModule(PatronsModule.class).getUserPatrons(patronsId);
            if (userPatrons == null) {
                return GameErrorCode.E_VARIETY_PATRONS_NOT_HAVE;
            }
            PatronsInfo patronsInfo = PatronsMgr.getPatronsInfo(userPatrons.getPatronsId());
            if (patronsInfo == null) {
                return GameErrorCode.E_PATRONS_NO_FOUND;
            }
            if (occupation != 0 && patronsInfo.getOccupation() != occupation) {
                return GameErrorCode.E_VARIETY_DISPATCH_PATRONS_OCCUPATION_ERROR;
            }
            if (!dataMap.containsKey(patronsId)) {
                initMatchPatronsData(patronsId);
            }
            MatchPatronsData data = dataMap.get(patronsId);
            recoveryPatronsBattleTimes(data);
            //没有参赛次数
            if (data.getMatchBattleTimes() + data.getPreMatchBattleTimes() >= GameConfig.VARIETY_PATRONS_WEEK_BATTLE_TIMES) {
                return GameErrorCode.E_VARIETY_PATRONS_BATTLE_TIMES_NO_ENOUGH;
            }
        }
        return 0;
    }

    /**
     * 请求发奖
     */
    public void getReward() {
        int todayTimeId = Integer.parseInt(DateHelper.getPyyyyMMddDateString(System.currentTimeMillis() / 1000));
        Map<Integer, List<Integer>> needRewardMap = checkNeedRewardMap();
        boolean needCrossCheck = false;
        if (needRewardMap.size() == 0) {
            if (matchTimeDataMap.containsKey(todayTimeId)) {
                for (MatchTimeData data : matchTimeDataMap.get(todayTimeId).values()) {
                    if (data.getGetRewardTime() == 0) {
                        needCrossCheck = true;
                    }
                }
            }
            //不用发奖
            if (!needCrossCheck) {
                VarietyProto.GetRewardRespMsg.Builder builder = VarietyProto.GetRewardRespMsg.newBuilder();
                builder.setRet(0);
                player.sendPacket(ClientProtocol.U_VARIETY_GET_REWARD, builder);
                return;
            }
        }
        //请求跨服发奖
        VarietyProto.GetRewardCrossReqMsg.Builder builder = VarietyProto.GetRewardCrossReqMsg.newBuilder();
        for (Map.Entry<Integer, List<Integer>> entry : needRewardMap.entrySet()) {
            for (Integer id : entry.getValue()) {
                VarietyProto.GetRewardData.Builder data = VarietyProto.GetRewardData.newBuilder();
                data.setDispatchTimeId(entry.getKey());
                data.setId(id);
                builder.addGetRewardData(data);
            }
        }
        if (!needRewardMap.containsKey(todayTimeId) && matchTimeDataMap.containsKey(todayTimeId)) {
            for (MatchTimeData matchTimeData : matchTimeDataMap.get(todayTimeId).values()) {
                if (matchTimeData.getGetRewardTime() == 0) {
                    VarietyProto.GetRewardData.Builder data = VarietyProto.GetRewardData.newBuilder();
                    data.setDispatchTimeId(matchTimeData.getDispatchTimeId());
                    data.setId(matchTimeData.getId());
                    builder.addGetRewardData(data);
                }
            }
        }
        player.sendPacket(CrossProtocol.C_VARIETY_GET_REWARD, builder);
    }


    /**
     * 跨服发奖返回
     *
     * @param msg
     */
    public void getRewardFromCross(VarietyProto.GetRewardCrossRespMsg msg) {
        // 当前时间是否是周日
        boolean needAddToNextWeek = isSunDayEndTime();
        Calendar now = Calendar.getInstance();
        Date monday = DateHelper.getThisWeekMonday(now.getTime());
        now.setTime(monday);
        int thisWeekId = parseTimeId(now.getTimeInMillis());
        now.add(Calendar.DATE, 7);
        int nextWeekId = parseTimeId(now.getTimeInMillis());
        Map<Integer, BigInteger> rankValueMap = new HashMap<>();
        VarietyProto.GetRewardRespMsg.Builder builder = VarietyProto.GetRewardRespMsg.newBuilder();
        builder.setRet(0);
        if (msg == null) {
            player.sendPacket(ClientProtocol.U_VARIETY_GET_REWARD, builder);
            return;
        }
        //根据排行获得奖励
        for (VarietyProto.VarietyMyRank myRank : msg.getRankList()) {
            MatchReward reward = MatchMgr.getReward(myRank.getLevel(), myRank.getMatchId(), myRank.getIndex());
            if (reward != null) {
                Map<Integer, MatchTimeData> map = matchTimeDataMap.get(myRank.getTimeId());
                if (map != null) {
                    MatchTimeData matchTimeData = map.get(myRank.getId());
                    if (matchTimeData != null) {
                        if (matchTimeData.getGetRewardTime() > 0) {
                            continue;
                        }
                        matchTimeData.setGetRewardTime(System.currentTimeMillis());
                    }
                }
                //门客百业经验奖励
                Property patronsReward = PropertyHelper.parseStringToProperty(reward.getPatronsRewards());
                long baiYeExpReward = patronsReward.getCountByGoodsId(GameConfig.PATRONS_BAIYE_EXP_ID).longValue();
                //派遣的门客领奖
                for (Integer patronsId : myRank.getPatronsIdList()) {
                    UserPatrons patrons = player.getModule(PatronsModule.class).getUserPatrons(patronsId);
                    if (patrons != null) {
                        patrons.setBaiYeExp(patrons.getBaiYeExp() + baiYeExpReward);
                        player.getModule(PatronsModule.class).syncPatronsData(patrons);
                    }
                }
                //玩家奖励
                Property rewardProperty = PropertyHelper.parseStringToProperty(reward.getPlayerRewards());
                player.getModule(CurrencyModule.class).addCurrency(rewardProperty,
                        eLogMoneyType.Variety, eLogMoneyType.VarietyGetReward);
                builder.addReward(VarietyPb.parseVarietyReward(myRank, reward));
                //领取的声望值计入周榜
                if (myRank.getTimeId() == parseTimeId(System.currentTimeMillis()) && needAddToNextWeek) {
                    if (!rankValueMap.containsKey(nextWeekId)) {
                        rankValueMap.put(nextWeekId, BigInteger.ZERO);
                    }
                    rankValueMap.put(nextWeekId, rankValueMap.get(nextWeekId).add(rewardProperty.getCountByGoodsId(GameConfig.GAME_MONEY_PRESTIGE)));
                } else if (myRank.getTimeId() >= thisWeekId && !needAddToNextWeek) {
                    if (!rankValueMap.containsKey(thisWeekId)) {
                        rankValueMap.put(thisWeekId, BigInteger.ZERO);
                    }
                    rankValueMap.put(thisWeekId, rankValueMap.get(thisWeekId).add(rewardProperty.getCountByGoodsId(GameConfig.GAME_MONEY_PRESTIGE)));
                }
            }
            addRankLog(myRank);
        }
        player.sendPacket(ClientProtocol.U_VARIETY_GET_REWARD, builder);
        //通知周榜变动
        for (Map.Entry<Integer, BigInteger> entry : rankValueMap.entrySet()) {
            addRewardState(entry.getKey(), entry.getValue().longValue());
//            MatchServerGroup group = MatchServerGroupMgr.getServerGroupByServerId(GameServer.getInstance().getServerId());
//            int groupId = group == null ? 0 : group.getGroupId();
            long groupId = GameServer.getInstance().getServerId();
            VarietyProto.RankChangeCrossReqMsg.Builder reqMsg = VarietyProto.RankChangeCrossReqMsg.newBuilder();
            reqMsg.setGroupId(groupId);
            reqMsg.setWeekId(entry.getKey());
            reqMsg.setPlayerBaseData(PlayerPb.parsePlayerBaseTempMsg(player.getUserInfo()));
            reqMsg.setValue( rewardStateMap.get(entry.getKey()).getValue());
            player.sendPacket(CrossProtocol.C_VARIETY_RANK_CHANGE, reqMsg);
        }
    }

    /**
     * 排行日志
     * @param myRank
     */
    private void addRankLog(VarietyProto.VarietyMyRank myRank) {
        try {
            LogMgr.addLogVarietyRank(new LogVarietyRank(getUserId(), myRank.getType(), myRank.getLevel(), myRank.getIndex(), myRank.getTimeId()));
        } catch (Exception e) {
            log.error("add varietyRank log error,userId:{}", getUserId());
        }
    }

    /**
     * 增加周榜数据
     * @param weekId
     * @param value
     */
    public void addRewardState(int weekId, long value) {
        if (!rewardStateMap.containsKey(weekId)) {
            MatchWeekRankRewardState rewardState = new MatchWeekRankRewardState();
            rewardState.setUserId(getUserId());
            rewardState.setGetReward(false);
            rewardState.setGetRewardTime(System.currentTimeMillis());
            rewardState.setWeekId(weekId);
            rewardState.setValue(0L);
            rewardState.setInsertOption();
            rewardStateMap.put(weekId, rewardState);
        }
        rewardStateMap.get(weekId).setValue(rewardStateMap.get(weekId).getValue() + value);
    }

    /**
     * 获取当前 前n天的日期
     *
     * @param n
     * @return
     */
    public static int getLastNDayTimeId(int n) {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -n);
        return Integer.parseInt(DateHelper.getPyyyyMMddDateString(cal.getTimeInMillis() / 1000));
    }

    /**
     * 初始化杂艺门客数据
     *
     * @param patronsId 门客id
     */
    private void initMatchPatronsData(int patronsId) {
        MatchPatronsData data = new MatchPatronsData();
        data.setUserId(getUserId());
        data.setPatronsId(patronsId);
        data.setMatchBattleTimes(0);
        data.setPreMatchBattleTimes(0);
        data.setRecoveryTime(System.currentTimeMillis());
        data.setBattleTimeId(0);
        data.setInsertOption();
        dataMap.put(data.getPatronsId(), data);
    }

    /**
     * 同步杂艺门客出战次数
     */
    public void syncVarietyPatrons() {
        Calendar cal = Calendar.getInstance();
        if (!checkIsOverDispatchTime()) {
            //当前不是领奖期 则往前推一天
            cal.add(Calendar.DATE, -1);
        }
        VarietyProto.SyncVarietyPatronsDataRespMsg.Builder builder = VarietyProto.SyncVarietyPatronsDataRespMsg.newBuilder();
        for (MatchPatronsData patronsData : dataMap.values()) {
            recoveryPatronsBattleTimes(patronsData);
            if (patronsData.getMatchBattleTimes() > 0) {
                VarietyProto.VarietyPatronsData.Builder data = VarietyProto.VarietyPatronsData.newBuilder();
                data.setPatronsId(patronsData.getPatronsId());
                data.setBattleTimes(patronsData.getMatchBattleTimes());
                data.setIsBattle(patronsData.getBattleTimeId() == Integer.parseInt(DateHelper.getPyyyyMMddDateString(cal.getTimeInMillis() / 1000)));
                builder.addPatrons(data);
            }
        }
        player.sendPacket(ClientProtocol.U_VARIETY_SYNC_VARIETY_PATRONS, builder);
    }

    /**
     * 门客每周恢复出战次数
     *
     * @param patronsData
     */
    public void recoveryPatronsBattleTimes(MatchPatronsData patronsData) {
        if (!DateHelper.isSameWeek(patronsData.getRecoveryTime() / 1000, System.currentTimeMillis() / 1000)) {
            patronsData.setMatchBattleTimes(0);
            patronsData.setBattleTimeId(0);
            patronsData.setRecoveryTime(System.currentTimeMillis());
        }
    }

    /**
     * 红点同步
     */
    public void syncRedPot() {
        VarietyProto.VarietyRedPot.Builder respMsg = VarietyProto.VarietyRedPot.newBuilder();
        int weekId = getLastWeekId(2);
        boolean sendCross = weekRankRedPot(weekId);
        respMsg.setWeekGetReward(sendCross);
        //游戏服先判断是否可以领奖
        if (checkNeedRewardMap().size() > 0) {
            respMsg.setGetReward(true);
        } else {
            sendCross = true;
        }
        if (sendCross) {
            //发送跨服判断
            respMsg.setWeekId(weekId);
            respMsg.setGetReward(false);
            player.sendPacket(CrossProtocol.C_VARIETY_SYNC_VARIETY_RED_POT, respMsg);
            return;
        }
        player.sendPacket(ClientProtocol.U_VARIETY_SYNC_RED_POT, respMsg);
    }

    /**
     * 周榜红点
     * @return
     */
    public boolean weekRankRedPot(int weekId) {
        if (!isInWeekRankRewardTime(2, weekId)) {//不在领奖期
            return false;
        }
        MatchWeekRankRewardState rewardState = rewardStateMap.get(weekId);
        if(rewardState == null){
            return true;
        }
        if (rewardState.isGetReward()) {
            return false;
        }
        return true;
    }

    /**
     * 是否需要发奖
     *
     * @return
     */
    public Map<Integer, List<Integer>> checkNeedRewardMap() {
        Map<Integer, List<Integer>> needRewardMap = new HashMap<>(); //dispatchTimeId - id
        Calendar cal = Calendar.getInstance();
        //当前不是领奖期 则往前推一天
        if (checkIsInDispatchTime()) {
            cal.add(Calendar.DATE, -1);
        }
        //系统截止当前可领奖的最后时间id
        int needGetRewardTimeId = Integer.parseInt(DateHelper.getPyyyyMMddDateString(cal.getTimeInMillis() / 1000));
        //奖励留存天数
        int rewardSaveDays = MatchMgr.rewardSaveDays;
        int lastNDayTimeId = getLastNDayTimeId(rewardSaveDays);
        for (Map<Integer, MatchTimeData> map : matchTimeDataMap.values()) {
            for (MatchTimeData matchTimeData : map.values()) {
                if (matchTimeData.getDispatchTimeId() <= needGetRewardTimeId && matchTimeData.getGetRewardTime() == 0 && matchTimeData.getDispatchTimeId() > lastNDayTimeId) {
                    if (!needRewardMap.containsKey(matchTimeData.getDispatchTimeId())) {
                        needRewardMap.put(matchTimeData.getDispatchTimeId(), new ArrayList<>());
                    }
                    needRewardMap.get(matchTimeData.getDispatchTimeId()).add(matchTimeData.getId());
                }
            }
        }
        return needRewardMap;
    }

    /**
     * 分组变更造成的系统开启
     */
//    public void crossServerGroupReload() {
//        if (SystemOpenMgr.systemOpen(player, eSystemId.Variety.getValue())) {
//            //同步玩家杂艺门客出战次数
//            syncVarietyPatrons();
//            //同步区服分组
//            VarietyProto.SyncGroupServerReqMsg.Builder groupServerListSyncMsg = VarietyProto.SyncGroupServerReqMsg.newBuilder();
//            player.sendChannelPacket(CrossProtocol.C_VARIETY_SYNC_GROUP_SERVER_LIST, groupServerListSyncMsg);
//        }
//    }

    /**
     * 是否在周榜领奖期
     *
     * @param type
     * @return
     */
    public boolean isInWeekRankRewardTime(int type, int weekId) {
        int timeId = parseTimeId(System.currentTimeMillis());
        if (type == 2) {
            if (timeId - weekId < 0 || timeId - weekId > 13) {
                return false;
            }
            Calendar cal = Calendar.getInstance();
            if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
                if (timeId - weekId < 7) {
                    return checkIsLastRewardTime();
                } else {
                    return !checkInCanRewardTime();
                }
            }
            if (timeId - weekId >= 7) {
                return true;
            }
        }
        return false;
    }

    /**
     * 是否是周日并且是赛事结束时间之后
     * @return
     */
    public boolean isSunDayEndTime() {
        Calendar cal = Calendar.getInstance();
        return cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY && checkIsLastRewardTime();
    }

    /**
     * 是否是可以领奖时间
     *
     * @param type
     * @param weekId
     * @return
     */
    public boolean isInCanRewardTime(int type, int weekId) {
        int timeId = parseTimeId(System.currentTimeMillis());
        if (type == 2) {
            Calendar cal = Calendar.getInstance();
            if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY && timeId - weekId < 7) {
                return checkInCanRewardTime();
            }
        }
        return true;
    }

    /**
     * 获取上周id 如果是周日晚赛事结束之后则为下一周 上周id则是本周id
     * @param type
     * @return
     */
    public int getLastWeekId(int type) {
        if (type == 2) {
            Calendar now = Calendar.getInstance();
            Date monday = DateHelper.getThisWeekMonday(now.getTime());
            now.setTime(monday);
            // 当前时间是否是周日
            if (!isSunDayEndTime()) {
                now.add(Calendar.DATE, -7);
            }
            return parseTimeId(now.getTimeInMillis());
        }
        return 0;
    }

    /**
     * 根据类型获取排行榜的weekId
     * @param type 1本周2上周
     * @return
     */
    public int getRankListWeekIdByType(int type) {
        Calendar now = Calendar.getInstance();
        Date monday = DateHelper.getThisWeekMonday(now.getTime());
        now.setTime(monday);
        int thisWeekId = Integer.valueOf(DateHelper.getPyyyyMMddDateString(now.getTimeInMillis() / 1000));
        now.add(Calendar.DATE, 7);
        int nextWeekId = Integer.valueOf(DateHelper.getPyyyyMMddDateString(now.getTimeInMillis() / 1000));
        now.add(Calendar.DATE, -14);
        int preWeekId = Integer.valueOf(DateHelper.getPyyyyMMddDateString(now.getTimeInMillis() / 1000));
        if (type == 1) {
            //本周
            if (isSunDayEndTime()) {
                return nextWeekId;
            } else {
                return thisWeekId;
            }
        } else if (type == 2) {
            if (isSunDayEndTime()) {
                return thisWeekId;
            } else {
                return preWeekId;
            }
        }
        return 0;
    }


    /**
     * 领取周榜奖励
     */
    public MatchRewardResult getMatchRewardResult(int type, boolean isCrossNotify, int myRank) {
        MatchRewardResult result = new MatchRewardResult();
        int weekId = getRankListWeekIdByType(type);
        if (type != 2) {
            result.setRet(GameErrorCode.E_VARIETY_NO_IN_GET_REWARD_TIME);
            return result;
        }

        if (!isInWeekRankRewardTime(type, weekId)) {//不在领奖期
            result.setRet(GameErrorCode.E_VARIETY_NO_IN_GET_REWARD_TIME);
            return result;
        }
        //结算5分钟
        if (!isInCanRewardTime(type, weekId)) {
            result.setRet(GameErrorCode.E_VARIETY_IN_REWARD_SETTLEMENT_TIME);
            return result;
        }
        //没有参赛
        MatchWeekRankRewardState rewardState = rewardStateMap.get(weekId);
        if(rewardState == null){
            addRewardState(weekId, 0);
            rewardState = rewardStateMap.get(weekId);
        }
        //已经领过奖
        if (rewardState.isGetReward()) {
            result.setRet(GameErrorCode.E_VARIETY_REWARD_IS_GET);
            return result;
        }
        if(!isCrossNotify) {
            //发送请求到跨服获取排名
            VarietyProto.GetWeekRankRewardCrossReqMsg.Builder reqMsg = VarietyProto.GetWeekRankRewardCrossReqMsg.newBuilder();
//            int groupId = 0;
//            MatchServerGroup group = MatchServerGroupMgr.getServerGroupByServerId(GameServer.getInstance().getServerId());
//            if (group != null) {
//                groupId = group.getGroupId();
//            }
            long groupId = GameServer.getInstance().getServerId();
            reqMsg.setWeekId(weekId);
            reqMsg.setGroupId(groupId);
            reqMsg.setType(type);

            YanQuMessage pkg = YanQuMessageUtils.buildMessage(CrossProtocol.C_VARIETY_GET_WEEK_RANK_REWARD, reqMsg);
            GamePlayerMgr.sendPacket(player.getUserId(), pkg);
            return result;
        }else {
            if (myRank == 0) {
                result.setRet(GameErrorCode.E_VARIETY_RANK_REWARD_NO_COMPLETE);
                return result;
            }
            List<String> rankRewards = parseWeekRankReward(myRank, rewardState.getValue());
            if (rankRewards.size() <= 0) {
                result.setRet(GameErrorCode.E_VARIETY_RANK_REWARD_NO_COMPLETE);
                return result;
            }
            //添加奖励
            rewardState.setGetReward(true);
            rewardState.setGetRewardTime(System.currentTimeMillis());
            Property rankReward = new Property();
            rankReward.addProperty(PropertyHelper.parseStringToProperty(rankRewards.get(0)));
            if (rankRewards.size() >= 2) {
                rankReward.addProperty(PropertyHelper.parseStringToProperty(rankRewards.get(1)));
                result.setGoalReward(rankRewards.get(1));
            }
            player.getModule(CurrencyModule.class).addCurrency(rankReward, eLogMoneyType.Variety, eLogMoneyType.VarietyGetWeekRankReward);
            result.setReward(rankRewards.get(0));
            result.setRet(0);
            return result;
        }
    }

    /**
     * 解析周榜奖励
     *
     * @param myRank
     * @return
     */
    public List<String> parseWeekRankReward(int myRank, long value) {
        List<String> rewards = new ArrayList<>();
        String rankRewardStr = GameConfig.VARIETY_WEEK_RANK_REWARD;
        String[] paramArr = rankRewardStr.split("\\|");
        for (String str : paramArr) {
            String[] split = str.split("#");
            String[] rankArr = split[0].split(",");
            List<String> goalList = new ArrayList<>();
            if (split.length >= 2) {
                String[] goalArr = split[1].split(",");
                goalList.add(0, goalArr[0]);
                goalList.add(1, goalArr[1]);
            }
            if ((myRank >= Integer.parseInt(rankArr[0])) && (myRank <= Integer.parseInt(rankArr[1]))) {
                rewards.add(rankArr[2]);
                if (goalList.size() >= 2) {
                    if (BigInteger.valueOf(value).compareTo(new BigInteger(goalList.get(0))) >= 0) {
                        rewards.add(goalList.get(1));
                    }
                }
                break;
            }
        }
        return rewards;
    }

    /**
     * 同步数据上跨服
     *
     * @param patronsList
     */
    public void syncPatronsAbility(List<UserPatrons> patronsList) {
        int todayTimeId = Integer.parseInt(DateHelper.getPyyyyMMddDateString(System.currentTimeMillis() / 1000));
        //当日没有派遣就不用同步上跨服了
        if (!matchTimeDataMap.containsKey(todayTimeId)) {
            return;
        }
        //派遣期才同步
        if (checkIsInDispatchTime()) {
            VarietyProto.SyncCrossPatronsAbilityMsg.Builder syncMsg = VarietyProto.SyncCrossPatronsAbilityMsg.newBuilder();
            for (UserPatrons patrons : patronsList) {
                VarietyProto.SyncPatronsTemp.Builder syncPatronsTemp = VarietyProto.SyncPatronsTemp.newBuilder();
                syncPatronsTemp.setPatronsId(patrons.getPatronsId());
                syncPatronsTemp.setAbility(patrons.getAbility().longValue());
                syncMsg.addSyncPatronsTemp(syncPatronsTemp);
            }
            player.sendPacket(CrossProtocol.C_VARIETY_SYNC_PATRONS_ABILITY, syncMsg);
        }
    }
}
